from sqlalchemy.orm import Session
from app.models.post import Post, PostMedia, PostLike, Comment, Tag
from app.schemas.post import PostCreate, PostUpdate, CommentCreate
from typing import List, Optional

def get_post(db: Session, post_id: int) -> Optional[Post]:
    """获取指定ID的帖子"""
    return db.query(Post).filter(Post.id == post_id, Post.is_deleted == False).first()

def get_posts(
    db: Session, 
    skip: int = 0, 
    limit: int = 100,
    user_id: Optional[int] = None,
    campsite_id: Optional[int] = None,
    is_published: bool = True
) -> List[Post]:
    """获取帖子列表，可按用户ID或营地ID过滤"""
    query = db.query(Post).filter(Post.is_deleted == False)
    
    if is_published:
        query = query.filter(Post.is_published == True)
    
    if user_id:
        query = query.filter(Post.author_id == user_id)
    
    if campsite_id:
        query = query.filter(Post.campsite_id == campsite_id)
    
    return query.order_by(Post.created_at.desc()).offset(skip).limit(limit).all()

def create_post(db: Session, post: PostCreate, user_id: int) -> Post:
    """创建新帖子"""
    # 创建帖子对象
    db_post = Post(
        title=post.title,
        content=post.content,
        author_id=user_id,
        campsite_id=post.campsite_id,
    )
    
    db.add(db_post)
    db.commit()
    db.refresh(db_post)
    
    # 添加媒体
    if post.media:
        for i, media_item in enumerate(post.media):
            db_media = PostMedia(
                post_id=db_post.id,
                media_type=media_item.media_type,
                url=media_item.url,
                thumbnail_url=media_item.thumbnail_url,
                order=media_item.order or i
            )
            db.add(db_media)
    
    # 添加标签
    if post.tags:
        for tag_name in post.tags:
            # 查找或创建标签
            db_tag = db.query(Tag).filter(Tag.name == tag_name).first()
            if not db_tag:
                db_tag = Tag(name=tag_name)
                db.add(db_tag)
                db.commit()
                db.refresh(db_tag)
            
            # 添加到帖子的标签列表
            db_post.tags.append(db_tag)
    
    db.commit()
    db.refresh(db_post)
    return db_post

def update_post(db: Session, post_id: int, post_update: PostUpdate, user_id: int) -> Optional[Post]:
    """更新帖子"""
    db_post = db.query(Post).filter(Post.id == post_id, Post.author_id == user_id, Post.is_deleted == False).first()
    if not db_post:
        return None
    
    # 更新帖子数据
    update_data = post_update.dict(exclude_unset=True)
    for key, value in update_data.items():
        setattr(db_post, key, value)
    
    db.commit()
    db.refresh(db_post)
    return db_post

def delete_post(db: Session, post_id: int, user_id: int) -> bool:
    """删除帖子（软删除）"""
    db_post = db.query(Post).filter(Post.id == post_id, Post.author_id == user_id, Post.is_deleted == False).first()
    if not db_post:
        return False
    
    db_post.is_deleted = True
    db.commit()
    return True

def like_post(db: Session, post_id: int, user_id: int) -> Optional[PostLike]:
    """点赞帖子"""
    # 检查帖子是否存在
    db_post = get_post(db, post_id)
    if not db_post:
        return None
    
    # 检查是否已点赞
    existing_like = db.query(PostLike).filter(
        PostLike.post_id == post_id,
        PostLike.user_id == user_id
    ).first()
    
    if existing_like:
        return existing_like
    
    # 创建点赞记录
    db_like = PostLike(post_id=post_id, user_id=user_id)
    db.add(db_like)
    
    # 更新帖子点赞计数
    db_post.like_count += 1
    
    db.commit()
    db.refresh(db_like)
    return db_like

def unlike_post(db: Session, post_id: int, user_id: int) -> bool:
    """取消点赞帖子"""
    # 查找点赞记录
    db_like = db.query(PostLike).filter(
        PostLike.post_id == post_id,
        PostLike.user_id == user_id
    ).first()
    
    if not db_like:
        return False
    
    # 删除点赞记录
    db.delete(db_like)
    
    # 更新帖子点赞计数
    db_post = get_post(db, post_id)
    if db_post and db_post.like_count > 0:
        db_post.like_count -= 1
    
    db.commit()
    return True

def create_comment(db: Session, post_id: int, user_id: int, comment: CommentCreate) -> Optional[Comment]:
    """创建评论"""
    # 检查帖子是否存在
    db_post = get_post(db, post_id)
    if not db_post:
        return None
    
    # 如果有父评论，检查是否存在
    if comment.parent_id:
        parent_comment = db.query(Comment).filter(Comment.id == comment.parent_id, Comment.post_id == post_id).first()
        if not parent_comment:
            return None
    
    # 创建评论
    db_comment = Comment(
        post_id=post_id,
        user_id=user_id,
        content=comment.content,
        parent_id=comment.parent_id
    )
    db.add(db_comment)
    
    # 更新帖子评论计数
    db_post.comment_count += 1
    
    db.commit()
    db.refresh(db_comment)
    return db_comment

def get_comments(db: Session, post_id: int, skip: int = 0, limit: int = 100) -> List[Comment]:
    """获取帖子的评论列表（顶层评论）"""
    return db.query(Comment).filter(
        Comment.post_id == post_id,
        Comment.parent_id == None,
        Comment.is_deleted == False
    ).order_by(Comment.created_at.desc()).offset(skip).limit(limit).all()

def increment_view_count(db: Session, post_id: int) -> bool:
    """增加帖子浏览次数"""
    db_post = get_post(db, post_id)
    if not db_post:
        return False
    
    db_post.view_count += 1
    db.commit()
    return True 